package org.example.lanchain.controller;

import org.example.lanchain.bean.User;
import org.example.lanchain.dto.LoginRequest;
import org.example.lanchain.dto.LoginResponse;
import org.example.lanchain.dto.RegisterRequest;
import org.example.lanchain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@Valid @RequestBody LoginRequest request) {
        try {
            LoginResponse response = userService.login(request);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", response.getSuccess());
            result.put("message", response.getMessage());
            
            if (response.getSuccess()) {
                result.put("token", response.getToken());
                result.put("userInfo", response.getUserInfo());
                result.put("expireTime", response.getExpireTime());
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "登录失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@Valid @RequestBody RegisterRequest request) {
        try {
            User user = userService.register(request);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "注册成功");
            result.put("userId", user.getId());
            result.put("username", user.getUsername());
            result.put("email", user.getEmail());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(HttpServletRequest request) {
        try {
            String token = extractToken(request);
            userService.logout(token);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登出成功");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "登出失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/user")
    public ResponseEntity<Map<String, Object>> getCurrentUser(HttpServletRequest request) {
        try {
            String token = extractToken(request);
            User user = userService.getUserByToken(token);
            
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "用户未登录或token已过期");
                return ResponseEntity.status(401).body(result);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("user", user);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取用户信息失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 验证token
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateToken(HttpServletRequest request) {
        try {
            String token = extractToken(request);
            boolean isValid = userService.validateToken(token);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", isValid);
            result.put("valid", isValid);
            
            if (!isValid) {
                result.put("message", "Token无效或已过期");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("valid", false);
            result.put("message", "Token验证失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username")
    public ResponseEntity<Map<String, Object>> checkUsername(@RequestParam String username) {
        try {
            User existingUser = userService.findByUsername(username);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("available", existingUser == null);
            result.put("message", existingUser == null ? "用户名可用" : "用户名已存在");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "检查用户名失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 检查邮箱是否可用
     */
    @GetMapping("/check-email")
    public ResponseEntity<Map<String, Object>> checkEmail(@RequestParam String email) {
        try {
            User existingUser = userService.findByEmail(email);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("available", existingUser == null);
            result.put("message", existingUser == null ? "邮箱可用" : "邮箱已存在");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "检查邮箱失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 从请求中提取token
     */
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 